#include "../ds_types.h"
#include "sq_stack.h"
#include <stdlib.h>
#include <string.h>

Status sqstack_init(sq_stack *s, size_t struct_size)
{
	s->base = malloc(STACK_INIT_SIZE * struct_size);
	if(!s->base) 
		exit(OVERFLOW);
	s->top = s->base;
	s->stacksize = STACK_INIT_SIZE;
	return SUCCESS;
}

Status push(sq_stack *s, const void *e, size_t struct_size)
{
	if(sqstack_length(s, struct_size) == s->stacksize){
		s->base = realloc(s->base,
			(s->stacksize+STACK_INCREMENT) * struct_size);
		if(!s->base) exit(OVERFLOW);
		s->top = s->base + s->stacksize * struct_size;
		s->stacksize += STACK_INCREMENT;
	}
	memcpy(s->top, e, struct_size);
	s->top += struct_size;
	return SUCCESS;
}

Status pop(sq_stack *s, void *e, size_t struct_size)
{
	if(sqstack_empty(s)) return ERROR;
	s->top -= struct_size;
	memcpy(e, s->top, struct_size);
	return SUCCESS;
}

Status sqstack_traverse(const sq_stack *s, Bool visit(const void*), size_t struct_size)
{
	void *p = s->base;
	while(p != s->top){
		if(!visit(p))
			exit(ERROR);
		p += struct_size;
	}
}
